use std::io::{Read, Write}; //
use std::net; //
use std::thread; //

fn process(mut socket: net::TcpStream) {
    let mut buf = [0u8; 1024];

    let readz = socket.read(&mut buf).expect("Failed to read from socket");

    if readz == 0 {
        println!("Remote side close the socket");
    } else {
        println!("Read bytes len: {}", readz);
    }

    let writez = socket
        .write(&buf[0..readz])
        .expect("Failed to write into socker");
    println!("Write bytes len: {}", writez);
}

fn main() {
    println!("Start Threading Server!");

    let listener = net::TcpListener::bind("127.0.0.1:5000").expect("Failed to bind tcp address");

    loop {
        match listener.accept() {
            Ok((socket, remote_addr)) => {
                thread::spawn(move || {
                    println!("Accept connection from {}", remote_addr);
                    process(socket);
                });
            }
            Err(err) => {
                eprintln!("Failed to accept connection, err: {}", err);
            }
        }
    }
}
